<?php

namespace App\Services;

use App\Exceptions\SysExceptions;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\HttpException;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\Kernel\Exceptions\RuntimeException;

class WechatServices
{

    private static $config = [
        'app_id' => 'wxbaf553129f46f40e',
        'secret' => 'c5e467d8b9aefb0d0c6bfb8ad1fec419',

        // 下面为可选项
        // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
        'response_type' => 'array',

        'log' => [
            'level' => 'debug',
            'file' => __DIR__.'/wechat.log',
        ],
    ];

    /**
     * @throws InvalidArgumentException
     * @throws HttpException
     * @throws SysExceptions
     * @throws InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws RuntimeException
     */
    public static function wechat_login($code = '', $iv = '', $encryptedData = '', $code2 = ''): array
    {
        $app = Factory::miniProgram(self::$config);
        $token = $app->access_token->getToken();
        $access_token = $token['access_token'];
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$access_token";
        $info = self::http_request($url,json_encode([
            'code'=>$code2
        ]));

        if(!checkIsHasField($info['phone_info'],'phoneNumber')){
            throw new SysExceptions('手机号不存在');
        }

        $session = $app->auth->session($code);
        Logger::info("====>",$session);
        if(checkIsHasField($session,'errcode')){
            throw new SysExceptions('登陆失败');
        }

        $openid = $session['openid'];
        $phone = $info['phone_info']['phoneNumber'];
        //获取手机号
        return [
            'phone'=>$phone,
            'openid'=>$openid
        ];
    }

    public static function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, TRUE);
            curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json'
            ));
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);

        return json_decode($output,true);
    }

    /**
     * @throws InvalidArgumentException
     * @throws RuntimeException|SysExceptions
     */
    public static function qr_code(array $array)
    {
        $app = Factory::miniProgram(self::$config);
        $response = $app->app_code->get('/pages/login/login?spread_id='.$array['user_id']);
        $filename = '';
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save(public_path().'/qr_code/','qr_code'.$array['user_id'].'.png');
        }
        if($filename == ''){
            throw new SysExceptions('生成失败');
        }
        return $_SERVER['SERVER_NAME'].'/qr_code/'.$filename;
    }


}
